package com.briup.pts.service.impl;

import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.Account;
import com.briup.pts.domain.dto.LoginUser;
import com.briup.pts.mapper.AccountMapper;
import com.briup.pts.service.AccountService;
import com.briup.pts.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class AccountServiceImpl implements AccountService {

    private final AccountMapper accountMapper;

    @Override
    public Map<String, String> login(LoginUser user) {
        // 对传入的用户进行数据校验，即与数据库中的数据进行比对
        String username = user.getUsername();
        String password = user.getPassword();

        Account account = accountMapper.queryByUsername(username);
        // 确定该用户是否存在
        if (account == null) {
            throw new ServiceException(ResultCode.USER_IS_NOT_EXISTS);
        }
        // 如果没有抛出异常，说明该用户存在，那继续比较密码是否一致
        if (!password.equals(account.getPassword())) {
            throw new ServiceException(ResultCode.PASSWORD_IS_ERROR);
        }
        // 校验该用户是否可用
        if (account.getStatus() != 1) {
            throw new ServiceException(ResultCode.ACCOUNT_IS_UNABLE);
        }

        // 上述操作都无误的情况下，表示登录成功，需要签发token
        Map<String, Object> claims = Map.of("userId", account.getAccountId(),
                "username", username);
        String token = JwtUtil.sign(claims);

        return Map.of("token",token);
    }

    @Override
    public Account queryById(String userId) {
        return accountMapper.queryById(userId);
    }
}
